<?php

namespace App\Http\Controllers;

use App\Http\Requests\GroupLiveCodeRequest;
use App\Models\GroupLiveCode as Model;
use Iamxcd\LaravelCRUD\Traits\HasCrud;
use Endroid\QrCode\Builder\Builder;
use Endroid\QrCode\Encoding\Encoding;
use Endroid\QrCode\ErrorCorrectionLevel\ErrorCorrectionLevelHigh;
use Endroid\QrCode\Writer\PngWriter;
use Illuminate\Support\Facades\File;

class GroupLiveCodeController extends Controller
{
    use HasCrud;

    public function __construct(Model $model)
    {
        $this->model = $model;
        $this->request = app(GroupLiveCodeRequest::class);

        $this->filterableFields = ['title', 'status'];
    }

    public function store()
    {
        $request = $this->request;
        $data = $request->validated();
        $model = $this->model->create($data);

        $qrcode =  $this->createQrcode($model->id);
        $model->update(['group_live_qr_code' => $qrcode]);

        return $this->responseMessage('创建成功');
    }

    private function createQrcode($id)
    {
        $data = url('group/' . $id);
        $result = Builder::create()
            ->writer(new PngWriter())
            ->data($data)
            ->encoding(new Encoding('UTF-8'))
            ->errorCorrectionLevel(new ErrorCorrectionLevelHigh())
            ->size(300)
            ->margin(10)
            ->build();
        $path =  'qrcode/' . date('Y/m/d', now()->timestamp);

        if (!File::exists($path)) {
            File::makeDirectory(public_path($path), 0755, true, true);
        }

        $fileName = $path . $id . '.png';
        $result->saveToFile(public_path($fileName));
        return url($fileName);
    }

    public function scanHandle($id)
    {
        $model = $this->model::query()->find($id);

        $model->update(['scan_count' => $model->scan_count + 1]);
        
        return view('group', ['data' => $model]);
    }
}
